package com.ylyr.routerfunction.hadler;

import com.ylyr.routerfunction.domain.User;
import com.ylyr.routerfunction.exceptions.CheckException;
import com.ylyr.routerfunction.repository.UserRepository;
import com.ylyr.routerfunction.utils.CheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @Explain:
 * @Author: 30374
 * @Date: 2021/4/24
 */
@Component
public class UserHandler {

    @Autowired
    private UserRepository userRepository;

    /**
     * 得到所有用户信息
     *
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> getAllUser(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userRepository.findAll(), User.class);
    }

    /**
     * 新增用户
     *
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> createUser(ServerRequest serverRequest) {
        Mono<User> user = serverRequest.bodyToMono(User.class);

        return user.flatMap(u -> {
            CheckUtils.CheckException(u.getName());
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                    .body(userRepository.save(u), User.class);
        });
    }

    public Mono<ServerResponse> deleteUserById(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        return userRepository.findById(id).flatMap(user -> {
            return userRepository.delete(user).then(ServerResponse.ok().build());
        }).switchIfEmpty(ServerResponse.notFound().build());
    }

    public Mono<ServerResponse> findUserById(ServerRequest serverRequest) {
        String id = serverRequest.pathVariable("id");
        Mono<User> userMono = userRepository.findById(id);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(userRepository.findById(id),User.class);
    }
}
